﻿using System.Net;
using System.Net.Sockets;

namespace SeverMemory;

//服务器
public class ServerSocket
{
    //服务端的Socket对象
    private Socket serverSocket;
    public string ip = "127.0.0.1";
    public int port = 8888;
    //构造函数初始化
    public ServerSocket() {
        //初始化服务器端的Socket对象
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress ipAddress = IPAddress.Parse(ip);
        IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
        //ip地址和端号绑定到服务器上
        serverSocket.Bind(endPoint);
        //监听
        serverSocket.Listen(10);
        
        //等待客户端连接
        //不能在主线程等待，所以开启一个新线程
        Thread thread = new Thread(OnAccepClient);
        thread.Start();
    }
    
    public static List<ClientController> clientControllers = new List<ClientController>();

    private void OnAccepClient()
    {
        //循环检测是否有客户端连接
        while (true)
        {
            Console.WriteLine("Waiting for a client...");
            //阻塞，没有客户端连接时会阻塞在这一步
            Socket socket =  serverSocket.Accept();
            Console.WriteLine("Client accepted");
            //打印ip和端口号
            IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
            Console.WriteLine("客户端ip地址"+endPoint.Address+":端口号:"+endPoint.Port);
            
            ClientController controller = new ClientController(socket);
            clientControllers.Add(controller);
            
        }
    }
}